// pages/article/detail/detail.js
const app = getApp()
const util = require("../../../utils/util.js");
var pageNo;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        page: 1,
        pagecount: 1,
        showModalStatus: false,
        showNav: true, // 快捷导航是否展开
        showtk: false, // 是否显示外链客服弹框
        // showLink: false, // 是否显示复制链接弹框
        islongTap: false, // 判断长按复制点击事件是否可用
        // qrcodeimg: app.globalData.extConfig.qrcodeimg,
        collectCue: false,
        indexCue: true,
        recommlist: [],
        newlist: [],
        tAppid: app.globalData.tAppid,
        textraData: app.globalData.textraData,
        pageNo: 0,
        nodeData: [],
        showLoading: true,
        hotMessage: "",
        guessList: [],
        contentid: "",
        appImg: "",
        showHead: true,
        openShare: false,
        isCollect: false, //是否收藏
        platform: "kuaishou", // 用于判断运行环境，QQ浏览器单独过滤
        // canIUse: wx.canIUse('button.open-type.getUserInfo')
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        pageNo = 0;
        if (getCurrentPages().length > 1)
            this.setData({
                showIndex: true,
            });
        else
            this.setData({
                showIndex: false,
                navHeight: 350,
            });
        if (options.city == "wenda") {
            ks.redirectTo({
                url: '/pages/article/detail/detail?id=' + options.id + '&city=sz' + '&type=wenda',
            })
        }
        var sceneData = [];
        if (options.scene != undefined) {
            var scene = decodeURIComponent(options.scene);
            var arrPara = scene.split("/");
            for (var i in arrPara) {
                sceneData.push(arrPara[i])
            }
        }
        this.setData({
            contentid: sceneData[0] ? sceneData[0] : (options.id ? options.id : ''),
            citycode: sceneData[1] ? sceneData[1] : (options.city ? options.city : (ks.getStorageSync("citycode") ? ks.getStorageSync("citycode") : 'sz')),
            type: sceneData[2] ? sceneData[2] : (options.type ? options.type : ''),
            scene: (options.scene != undefined) ? options.scene : 0,
        });
        ks.setStorageSync('citycode', this.data.citycode)

        util.getUrl(app.globalData.url).then(() => {
            util.cityList().then((res) => {
                let citydata;
                if (res.allcity && Array.isArray(res.allcity))
                    citydata = res.allcity.filter(v => v.citycode == this.data.citycode);
                let cityname = (citydata && Array.isArray(citydata) && citydata[0]) ? citydata[0].cityname : ks.getStorageSync("city");
                this.setData({
                    city: cityname,
                })
                ks.setStorageSync('city', this.data.city)
            });

            // 热搜
            util.request('phb.php', {
                citycode: this.data.citycode,
            }, "GET").then(res => {
                if (res.data && Array.isArray(res.data)) {
                    if (res.data.length > 0) {
                        let hotmessage = res.data.splice(0, 3);
                        let index = 0;
                        this.setData({
                            hotMessage: hotmessage[0].title,
                        });
                        setInterval(() => {
                            ++index;
                            if (!hotmessage[index])
                                index = 0;
                            this.setData({
                                hotMessage: hotmessage[index].title,
                            });
                        }, 4000);

                    }
                }
            });
        })

        if (ks.getStorageSync("indexCue")) {
            this.setData({
                indexCue: false,
            })
        }


    },

    onShow() {
        util.getUrl(app.globalData.url).then((res) => {
            this.getContentData();
        });
    },



    // 内容的接口
    getContentData() {
        let contData = {
            citycode: this.data.type == 'wenda' ? 'wenda' : ((this.data.type == 'bsy' && this.data.citycode == 'sz') ? 'bsy' : this.data.citycode),
            action: 'content',
            id: this.data.contentid,
            path: "article",
        };
            // 判断是否是QQ浏览器环境
        if (ks.getSystemInfoSync().host && ks.getSystemInfoSync().host.env  ===  "SDK" && ks.getSystemInfoSync().host.appId  === "wx64f9cf5b17af074d") {
            this.setData({
                platform: "qq",
            });
        }

        util.request('index.php', contData, 'GET', this.data.platform).then(res => {

            if (res.data && res.data.app)
                this.setData({
                    appImg: res.data.app,
                });
            if (res.data.content) {
                let nodeData = res.data.content[0].content;
                let typelink = res.data.content[0].links.filter(v => v.type == 'link')
                if (typelink.length > 0) {
                    this.setData({
                        islongTap: true,
                    })
                }

                let collectValue = {
                    "id": res.data.id,
                    "title": res.data.title,
                    "classid": res.data.classid,
                    "classname": res.data.classname,
                    "images": res.data.images,
                    "publictime": res.data.publictime,
                    "nav": res.data.pagetype,
                };
                collectValue = encodeURIComponent(JSON.stringify(collectValue));
                this.setData({
                    articleId: res.data.id,
                    nodeData,
                    linkData: res.data.content[0].links,
                    title: res.data.title,
                    data: res.data,
                    author: res.data.author,
                    qrcode: res.data.qrcode ? res.data.qrcode : '',
                    site: {
                        'id': res.data.siteid,
                        'wapname': res.data.sitename
                    },
                    collectValue: collectValue,
                    articleData: {
                        id: this.data.contentid,
                        city: this.data.type == 'wenda' ? 'wenda' : ((this.data.type == 'bsy' && this.data.citycode == 'sz') ? 'bsy' : this.data.citycode),
                        title: res.data.title,
                        guide: res.data.guide ? res.data.guide : '',
                    }
                });
                if (res.data.title)
                    ks.setNavigationBarTitle({
                        title: res.data.title,
                    });

                if (!this.data.isCollect) {
                    this.isCollect(res.data.id);
                }
                this.getrecommlist(res.data.siteid, res.data.keywords);
                this.getnewlist(res.data.siteid);

                let guessList = res.data.tag ? res.data.tag.split(',') : [];
                if (res.data.keywords) {
                    this.getToolData(res.data.keywords);
                    guessList.unshift(res.data.keywords)
                }
                this.setData({
                    guessList,
                });

                if (res.data.keywords) {
                    this.getToolData(res.data.keywords);
                }
                let sceneData = ks.getLaunchOptionsSync().scene;
                // 文章数据统计
                ks.reportAnalytics('statistical_article', {
                    article_id: Number(this.data.contentid),
                    article_city: this.data.citycode,
                    article_type: this.data.type,
                    title: this.data.title,
                    article_scene: Number(this.data.scene ? this.data.scene : sceneData),
                    article_write: this.data.author,
                });

                this.setData({
                    showLoading: false,
                })

                // 添加足迹
                let footList = ks.getStorageSync("footList") ? ks.getStorageSync("footList") : [];
                let index = footList.findIndex(item => {
                    return item.id == this.data.contentid
                });
                if (index >= 0) {
                    let temp = footList[index];
                    footList.splice(index, 1);
                    footList.unshift(temp);
                } else {
                    footList.unshift({
                        id: this.data.contentid,
                        type: this.data.type,
                        month: new Date().getMonth() + 1,
                        year: new Date().getFullYear(),
                        day: new Date().getDate(),
                        date: util.formatTime(new Date()),
                        title: this.data.title
                    });
                }
                ks.setStorageSync("footList", footList);
            }
        })
    },
    // 富文本内容可点击的标签
    linkTap(e) {
        let url = e.detail.href;
        if (this.data.linkData != '') {
            let urlRes = [];
            urlRes = this.data.linkData.filter((v, k) => {
                var str = v.url;
                str = str.replace(/&amp;/g, "&");
                if (str == url) {
                    return v
                }
                // if (v.id != 0 && v.url == url) {
                //   return v
                // }
            })
            if (urlRes != '') {
                let id = urlRes[0].id;
                let type = urlRes[0].type;
                let citycode = urlRes[0].city ? urlRes[0].city : this.data.citycode;
                if (id != 0) {
                    ks.navigateTo({
                        url: '/pages/article/detail/detail?id=' + id + '&type=' + type + '&city=' + citycode,
                    });
                } else {
                    if (url.indexOf("mp.weixin.qq.com") != -1) {
                        ks.navigateTo({
                            url: '/pages/webview/webview?path=' + encodeURIComponent(url),
                        })
                    } else {
                        this.setData({
                            showtk: true
                        })
                        util.navContact(url, url)
                    }
                }
            } else {
                util.navContact(url, url)
            }
        }

    },
    link: function(e) {
        let id = e.currentTarget.dataset.id;
        let title = e.currentTarget.dataset.title;
        let url = e.currentTarget.dataset.url;
        let type = e.currentTarget.dataset.type;
        let citycode = e.currentTarget.dataset.citycode;
        if (id != 0 && url == "") {
            ks.navigateTo({
                url: '/pages/article/detail/detail?id=' + id + '&type=' + type + '&city=' + citycode,
            });
        } else {
            if (url.indexOf("mp.weixin.qq.com") != -1) {
                ks.navigateTo({
                    url: '/pages/webview/webview?path=' + encodeURIComponent(url),
                })
            } else {
                this.setData({
                    showtk: true
                })
                util.navContact(title, url)
            }

        }
    },

    // 相关工具服务接口
    getToolData(toolname) {
        let toolData = {
            action: "tools",
            city: this.data.city ? this.data.city : ks.getStorageSync("city"),
            keywords: toolname,
            version: app.globalData.version,
            type: "detail",
            size: 5,
            path: "article",
            valueid: this.data.contentid,
            pagetype: this.data.data.pagetype,
        };
        util.request('service.php', toolData, ).then(res => {
            if (res.data.state && res.data.data) {
                let head;
                res.data.data.forEach((tool, index) => {
                    if (tool.path.includes("topicality/subtopic/subtopic")) head = res.data.data.splice(index, 1)
                });
                this.setData({
                    toolArray: res.data.data,
                    head,
                });
            }

        })
    },

    // 相关阅读的接口
    getrecommlist(siteid, keywords) {
        let recommData = {
            citycode: this.data.type == 'wenda' ? 'wenda' : ((this.data.type == 'bsy' && this.data.citycode == 'sz') ? 'bsy' : this.data.citycode),
            action: 'list',
            pagesize: 5,
            siteid: siteid,
            keywords: keywords,
            city: this.data.city ? this.data.city : ks.getStorageSync("city"),
            notid: this.data.contentid,
            path: "article",
        }
        util.request('index.php', recommData, 'GET').then(res => {
            this.setData({
                recommlist: res.data,
            })

        })
    },

    // 最新阅读的接口
    getnewlist(siteid) {
        let newData = {
            citycode: this.data.type == 'wenda' ? 'wenda' : ((this.data.type == 'bsy' && this.data.citycode == 'sz') ? 'bsy' : this.data.citycode),
            action: 'list',
            pagesize: 5,
            siteid: siteid,
            path: "article",
            city: this.data.city ? this.data.city : ks.getStorageSync("city"),
        };
        util.request('index.php', newData, 'GET').then(res => {
            this.setData({
                newlist: res.data,
            })
        })
    },

    // 判断是否已收藏
    isCollect(id) {
        let data = {
            action: "collect",
            option: "check",
            user_id: ks.getStorageSync("user_id"),
            valueid: id,
            openid: ks.getStorageSync("openid"),
        };

        util.request('user.php', data, 'POST').then(res => {
            let isCollect = res.data.state == 1 ? true : false
            let collectFlag = res.data.state;
            let scData = res.data.data;
            this.setData({
                isCollect,
                collectFlag,
                scData
            })
        })
    },

    // 取消（删除）收藏
    delCollect(id) {
        this.setData({
            isCollect: false
        })
        ks.showToast({
            title: "取消收藏"
        })

        // if (this.data.scData != '') {
        //     let scid = this.data.scData.id;
        let data = {
            action: "collect",
            option: "del",
            openid: ks.getStorageSync("openid"),
            // user_id: ks.getStorageSync("user_id"),
            valueid: id
        };
        util.request('user.php', data, 'POST').then(res => {
                // if (res.data.state == 1) {
                //     ks.showToast({
                //         title: "取消收藏"
                //     })
                // }
            })
            // }
    },
    // 收藏按钮
    collectBtn(e) {
        let id = e.currentTarget.dataset.id;
        if (ks.getStorageSync("user_id")) {
            if (!this.data.isCollect) {
                ks.navigateTo({
                    url: `/pages/collect/collect?ids=${this.data.contentid}&value=${this.data.collectValue}`,
                });
            } else {
                this.delCollect(id);
            }
        } else {
            ks.showModal({
                title: '温馨提示',
                content: '暂未登录，请登录',
                showCancel: true,
                cancelText: '取消',
                cancelColor: '#000000',
                confirmText: '确定',
                confirmColor: '#3CC51F',
                success: (result) => {
                    if (result.confirm) {
                        ks.navigateTo({
                            url: '/pages/mine/login/login',
                        });
                    }
                },
            });
        }
        if (!ks.getStorageSync("collectCue")) {
            ks.showModal({
                content: '返回首页后，点击“我的”即可查看已收藏的内容。',
                showCancel: false,
                confirmText: "我知道了"
            })
        }
        ks.setStorageSync("collectCue", "collectCue")
    },

    // 查看文章图片事件
    showImg() {
        let arr = [];
        if (this.data.data) {
            let allSrc = this.data.data.content[0].images;
            for (let i = 0; i < allSrc.length; i++) {
                arr.push(allSrc[i])
                this.setData({
                    imageArray: arr
                })
            }
            setTimeout(() => {
                ks.previewImage({
                    current: this.data.imageArray, // 当前显示图片的http链接   
                    urls: this.data.imageArray // 需要预览的图片http链接列表   
                })
            }, 500)
        }
    },
    // 查看工具服务专题
    seeBtn(e) {
        let path = e.currentTarget.dataset.path;
        let appid = e.currentTarget.dataset.appid;
        let linkname = e.currentTarget.dataset.title;
        let index = e.currentTarget.dataset.index;
        let data = this.data.toolArray[index];
        let title = util.getValue("title", e);
        if (path.indexOf("pages") == -1 && path.indexOf("mp.weixin.qq.com") == -1) {
            this.setData({
                showtk: true
            })
            util.navContact(linkname, path)
        } else {
            if (path.includes("topicality")) {
                let scene = util.getScene(ks.getLaunchOptionsSync().scene);
                util.navMethod(path, appid, title, scene);
            } else
                util.navMethod(path, appid);
        }

    },

    // 外链进入客服会话
    contact() {
        this.setData({
            showtk: false,
        })
    },

    // 外链弹框关闭
    close() {
        this.setData({
            showtk: false,
        })
    },

    // 分享按钮
    shareBtn(e) {
        this.setData({
            showModalStatus: true,
            openShare: false,
        })
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        return {
            title: this.data.data ? this.data.data.title : '',
            imageUrl: this.data.data ? this.data.data.images : '',
            path: 'pages/article/detail/detail?id=' + this.data.contentid + '&city=' + this.data.citycode + '&type=' + this.data.type
        }
    },

    onShareTimeline: function() {
        return {
            title: this.data.data ? this.data.data.title : '',
            imageUrl: this.data.data ? this.data.data.images : 'http://imgbdb3.bendibao.com/xcxbdb/file/20212/9/20210209161843_68677.jpg',

        }
    },

    /**
     * 页面滑动事件的处理函数
     */
    onPageScroll: function(e) {
        if (e.scrollTop > 10 && this.data.showHead) {
            this.setData({
                showHead: false,
            });
        } else if (e.scrollTop < 6 && !this.data.showHead) {
            this.setData({
                showHead: true,
            });
        }
        if (!ks.getStorageSync("indexCue")) {
            ks.setStorageSync("indexCue", "indexCue")
        }
        if (this.data.showNav)
            this.setData({
                showNav: false,
            });
        if (!this.data.showNav && !this.data.indexCue)
            this.setData({
                showNav: false,
                indexCue: false,
            })
    },

    openShare() {
        this.setData({
            openShare: true,
        });
    },

    closeShare() {
        this.setData({
            openShare: false,
        })
    },

    seeMore() {
        if (this.type == "bsy") {
            ks.navigateTo({
                url: `/pages/article/list/list?id=${this.data.data.classid}&type=${this.data.data.pagetype}&city=${this.data.citycode}&menuIndex=0`
            })
        } else {
            ks.navigateTo({
                url: `/pages/article/channel/channel?id=${this.data.data.siteid}&type=${this.data.data.pagetype}&city=${this.data.citycode}`
            })
        }
    }
})